#ifndef MOTORCONTROLLER_H
#define MOTORCONTROLLER_H

#include <QObject>
#include <QSerialPort>
#include <QVector>
#include <QMap>
#include <QTimer>

class MotorController : public QObject
{
    Q_OBJECT
public:
    struct MotorSpeedParam {
        int addr;
        int direction;
    };

    struct MotorPositionParam {
        int addr;
        int direction;
        int position;
    };

    explicit MotorController(QObject *parent = nullptr);
    MotorController(const QString &port, int baudrate = 115200, 
                   int acceleration = 150, QObject *parent = nullptr);
    ~MotorController();

    bool open();
    void close();

    void setVelocity(int addr, int direction, int velocity, int acceleration = -1);
    void setPosition(int addr, int direction, int velocity, int position, bool absolute = true, int acceleration = -1);
    void stop(int addr);
    void originTriggerReturn(int addr, int o_mode, bool snF);
    void originSetZero(int addr, bool svF);

    void syncVelocity(const QVector<MotorSpeedParam> &motors, int velocity);
    void syncPosition(const QVector<MotorPositionParam> &motors, 
                     int velocity, bool absolute = true);

    // 预设动作
    void moveDown();
    void moveUp();
    void moveX(int position, int velocity = 100, int motor1_addr = 3, int motor1_dir = 0, 
               int motor2_addr = 4, int motor2_dir = 1, bool absolute = true);
    void moveXY(int x_position, int y_position, int velocity = 2000, bool absolute = true);
    void moveZ(int z_position, int velocity = 2000, bool absolute= true);
    void moveAxis(const QString &axis_name, int position, 
                 int velocity = 100, bool absolute = true);
    void moveAxis(const QStringList &axis_names, const QMap<QString, int> &positions, 
                 int velocity = 100, bool absolute = true);

private:
    bool sendData(const QByteArray &data);
    void syncEnable();

    QSerialPort *serialPort;
    QString portName;
    int baudRate;
    int defaultAcceleration;
};

#endif // MOTORCONTROLLER_H
